import { getMemorys, handleMemory, deleteMemorys } from "@/services"
import {
  IntlType,
  Key,
  PageContainer,
  ActionType,
  ProColumns,
  ProTable,
} from "@ant-design/pro-components"
import { Box } from "@mui/system"
import { useRequest } from "ahooks"
import { WxUploader } from "aling"
import {
  Button,
  DatePicker,
  Form,
  Divider,
  Modal,
  Switch,
  Input,
  message,
  Spin,
  Popconfirm,
  InputNumber,
} from "antd"
import { SortOrder } from "antd/es/table/interface"
import dayjs from "dayjs"
import React, { useEffect, useRef, useState } from "react"
const maxCount = 20
// 文件大小限制（单位：字节）
const MAX_FILE_SIZE = 200 * 1024 * 1024 // 200MB
export default () => {
  const [editStatus, setEditStatus] = useState<any>(null)
  const [selectStatus, setSelectStatus] = useState<any>(null)
  const [form] = Form.useForm()
  const [batchform] = Form.useForm()
  const Action = useRef<ActionType | undefined>(null)
  const { runAsync, loading } = useRequest((params) => getMemorys(params), {
    manual: true,
  })
  const { runAsync: deleteMyMemorys, loading: memoDeleteLoading } = useRequest(
    deleteMemorys,
    {
      manual: true,
      onSuccess(data, params) {
        Action.current?.reload()
        message.info("删除成功!")
      },
      onError(e, params) {
        message.error("删除失败！")
      },
    },
  )
  const requester = async (
    { current, pageSize, ...params }: any,
    sort: Record<string, SortOrder>,
    filter: Record<string, (string | number)[] | null>,
  ) => {
    const sortParams: any = {}
    Object.keys(sort)?.forEach?.((key) => {
      sortParams[key] = sort[key] === "ascend" ? "asce" : "desc"
    })
    const res = await runAsync({ pageSize, pageNo: current, ...sortParams })
    return res?.data
  }
  const columns: ProColumns<any>[] = [
    {
      title: "发布时间",
      dataIndex: "time",
      sorter: true,
      renderFormItem(schema, config, form, action) {
        console.log(schema, config, form, action)
        return (
          <DatePicker.RangePicker
            allowEmpty={[true, true]}
            onChange={(dates, datesring) => {}}
          />
        )
      },
      renderText(text, record, index, action) {
        return dayjs(parseInt(text))?.format("YYYY-MM-DD HH:mm:ss")
      },
    },
    {
      title: "位置",
      dataIndex: "location",
      renderText(text, record, index, action) {
        return text?.join("·") ?? "-"
      },
    },
    {
      title: "发布人",
      dataIndex: "nickname",
      renderText(text, record, index, action) {
        return text
      },
    },
    {
      title: "天气",
      dataIndex: "weather",
      renderText(text, record, index, action) {
        return text?.join("·") ?? "-"
      },
    },
    {
      title: "发表内容",
      dataIndex: "content",
    },
    {
      title: "是否隐藏",
      dataIndex: "hidden",
      tip: "是否在博客中显示该条记忆",
      valueType: "switch",
      render(dom, entity, index, action, schema) {
        return entity?.hidden ? "是" : "否"
      },
    },
    {
      title: "权重",
      dataIndex: "heart",
      width: 60,
      sorter: true,
      hideInSearch: true,
      renderText(text, record, index, action) {
        return text ?? "0"
      },
    },
    {
      title: "操作",
      dataIndex: "action",
      width: 160,
      hideInSearch: true,
      renderText(text, record, index, action) {
        return (
          <>
            <Box className="space-x-2">
              <Button
                type="link"
                onClick={() => {
                  setEditStatus({
                    ...record,
                    img:
                      record?.img?.map(
                        (item: string) =>
                          //url: "https://1.94.60.205/api/static/images/" + item,
                          window.alignConfig.blogSourceMinio +
                          "/memoryimage/" +
                          item,
                      ) || [],
                  })
                }}
              >
                编辑
              </Button>
              <Popconfirm
                title="确定删除该条记录吗?"
                onConfirm={() => deleteMyMemorys(record.id)}
              >
                <Button type="link" danger>
                  删除
                </Button>
              </Popconfirm>
            </Box>
          </>
        )
      },
    },
  ]
  const { runAsync: editMemory, loading: editMemoryLoading } = useRequest(
    handleMemory,
    {
      manual: true,
      onSuccess(data, params) {
        Action.current?.reload()
      },
    },
  )
  useEffect(() => {
    form.setFieldsValue(editStatus)
  }, [editStatus])
  return (
    <Box>
      <PageContainer
        style={{ minWidth: "fit-content" }}
        title={"记忆"}
        subTitle={"memories"}
      >
        <ProTable
          actionRef={Action}
          rowSelection={{
            type: "checkbox",
            onChange(selectedRowKeys, selectedRows, info) {
              setEditStatus(selectedRowKeys)
            },
            preserveSelectedRowKeys: true,
          }}
          rowKey={"id"}
          tableAlertOptionRender={({
            intl: IntlType,
            selectedRowKeys,
            selectedRows,
            onCleanSelected,
          }) => (
            <Box className="space-x-2">
              <Button
                type="primary"
                onClick={() => {
                  setEditStatus(selectedRows)
                }}
                size="small"
              >
                批量编辑
              </Button>
              <Divider type="vertical"></Divider>
              <Button danger type="primary" size="small">
                批量删除
              </Button>
              <Divider type="vertical"></Divider>
              <Button type="link" onClick={onCleanSelected}>
                取消选择
              </Button>
            </Box>
          )}
          columns={columns}
          loading={loading}
          request={requester}
        ></ProTable>
        <Spin spinning={editMemoryLoading}>
          <Modal
            title="编辑"
            okText={"保存"}
            onCancel={() => {
              setEditStatus(null)
            }}
            onOk={() => {
              form.validateFields().then((res) => {
                editMemory({ ...res, id: editStatus?.id })
                  .then((res) => {
                    setEditStatus(null)
                    message.success("保存成功")
                  })
                  .catch((e) => {
                    message.error("修改失败请重试")
                  })
              })
            }}
            open={editStatus}
          >
            <Form form={form}>
              <Form.Item name={"content"} label={"内容"}>
                <Input.TextArea rows={5} placeholder="请输入"></Input.TextArea>
              </Form.Item>
              <Form.Item name={"img"} label={"媒体文件"}>
                <WxUploader
                  action={"/api/upload/memories"}
                  //文件不得超过200m
                  beforeUpload={(file: any, fileList: any) => {
                    if (file.size > MAX_FILE_SIZE) {
                      message.error(
                        `文件大小不能超过 ${MAX_FILE_SIZE / (1024 * 1024)}MB`,
                      )
                      return false
                    }
                    console.log(file, fileList)
                  }}
                  multiple
                  //可上传视频音乐和图片
                  accept="image/*,video/*,audio/*"
                ></WxUploader>
              </Form.Item>
              <Form.Item
                name={"hidden"}
                valuePropName="checked"
                label={"在博客中隐藏"}
              >
                <Switch></Switch>
              </Form.Item>
              <Form.Item name={"heart"} label={"权重"}>
                <InputNumber step={1} min={0}></InputNumber>
              </Form.Item>
            </Form>
          </Modal>
        </Spin>
        <Modal
          title="批量编辑"
          okText={"保存"}
          destroyOnHidden
          onCancel={() => {
            setSelectStatus(null)
          }}
          onOk={() => {
            setSelectStatus(null)
          }}
          open={selectStatus}
        >
          <Form layout="vertical" form={batchform}>
            <Form.Item
              name={"hidden"}
              valuePropName="checked"
              label={"在博客中隐藏"}
            >
              <Switch></Switch>
            </Form.Item>
            <Form.Item name={"heart"} label={"权重"}>
              <Input type="number"></Input>
            </Form.Item>
          </Form>
        </Modal>
      </PageContainer>
    </Box>
  )
}
